<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\AlipayPaid as AlipayPaidOrderModel;
use app\payment\model\PaymentPaidCompany as PaymentPaidCompanyModel;
use app\payment\model\PaymentCash as PaymentCashModel;
use app\payment\model\AlipayPaidSimulationNotify as AlipayPaidSimulationNotifyModel;
use app\payment\model\Notify as NotifyModel;
use app\payment\model\Mconfig as MconfigModel;
use app\payment\model\Verificationcode as VerificationcodeModel;
use app\payment\model\Download as DownloadModel;
use app\user\model\User as UserModel;
use app\api\model\PaymentOrderAlipayPaid as PaymentOrderAlipayPaidModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 支付宝代付订单控制器
 */
class AlipayPaid extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'add', 'see', 'export', 'notify', 'sendverify', 'verify', 'analyse'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }

        if (in_array(request()->action(), ['simulation_notify', 'simulation_notify_add'])) {
            if (!$this->simulation_paid_notify_safe) {
                $this->error('NO');
            }
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->manual_paid_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'create_param') {
                    $map[$map_k1][1] = 'like';
                    $map[$map_k1][2] = '%' . $map[$map_k1][2] . '%';
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        // 管理商户开始
        if ($this->manage_merchant) {
            $sub_merchant = $this->manage_merchant;
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }
        // 管理商户结束

        $list_rows = input('list_rows', 10) >= 10 ? 10 : input('list_rows');
        // 数据列表
        $data_list = AlipayPaidOrderModel::where($map)->field(true)->order('create_time desc')->paginate($list_rows);

        $sum_count = $data_list->toArray()['total'];
        $sum_cash = AlipayPaidOrderModel::where($map)->sum('cash');
        $sum_cash /= 100;

        $sum_deduct_cash = AlipayPaidOrderModel::where($map)->sum('deduct_cash');
        $sum_deduct_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        // 所有的订单状态
        $all_order_status = [1 => '处理中', 2 => '成功', 3 => '失败', 4 => '异常'];

        // 代付公司
        $all_paid_company = pay_config('paid_company');
        // 代付公司子商户号
        $all_child_company = PaymentPaidCompanyModel::where(['paid_class' => [1, 2]])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        foreach ($all_child_company as $key => $value) {
            $all_config_group[strstr($key, 'Paid', true)] = $all_paid_company[strstr($key, 'Paid', true)];
        }

        $date = date('Y-m-d');
        $appidName = '';
        $class = true;
        if ($this->no_auth) {
            $appidName = $this->merchant_id;
            $class = false;
        }
        $all_appid = AlipayPaidOrderModel::appidName($appidName, $class);
        $search = [
            ['daterange:6', 'create_time', '发起时间', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '代付状态', '', '', $all_order_status],
            ['select:3', 'app_id', '所属应用', '', '', $all_appid],
            ['text:3', 'merchant_order_id', '商户订单号'],
            ['text:3', 'cash', '代付金额'],
            ['text:3', 'account', '支付宝帐号'],
            ['text:3', 'name', '姓名'],
            ['text:3', 'order_id', '平台订单号'],
            ['select:3', 'mode', '代付方式', '', '', ['0' => '自动', '1' => '手动']],
            ['select:3', 'company', '总代付公司', '', '', $all_config_group],
            ['select:3', 'child_company', '子公司名称', '', '', $all_child_company],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'create_param', '商户参数'],
            ['text:3', 'merchant_id', '商户号'],
        ];

        $items = [
            ['create_time', '发起时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_order_id', '商户订单号'],
            ['order_id', '平台订单号'],
            ['other_order_id', '第三方订单号'],
            ['user_id', '用户ID'],
            ['account_name', '帐号和姓名', 'callback', function ($value) {
                return $value['account'] . '<br/>' . $value['name'];
            }, '__data__', 'text-center'],
            ['app_id', '应用名称', 'callback', function ($value) {
                return $value ? AlipayPaidOrderModel::appName($value) : '';
            }, '', 'text-center'],
            ['cashs', '代付和扣除', 'callback', function ($value) {
                return $value['cash'] / 100 . '<br/>' . $value['deduct_cash'] / 100;
            }, '__data__', 'text-center'],
            ['update_time', '完成时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status', '', $all_order_status],
            ['child_company', '子公司', 'callback', function ($child_company, $all_child_company) {
                return isset($all_child_company[$child_company]) ? $all_child_company[$child_company] : $child_company;
            }, $all_child_company],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[9]);
            unset($search[10]);
            unset($search[11]);
            unset($search[12]);
            unset($search[13]);
            // 去掉显示列
            unset($items[1]);
            unset($items[4]);
            unset($items[5]);
            unset($items[11]);
        }
        if ($this->is_agent) {
            // 显示搜索项
            $search[] = ['text:3', 'merchant_id', '商户号'];
            // 显示列
            array_unshift($items, ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center']);
        }

        $describe = [
            'title' => "总笔数：{$sum_count} 笔    取款金额：{$sum_cash} 元    扣除金额：{$sum_deduct_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        // 分析
        $analyse = [
            'title' => '分析',
            'icon' => 'fa fa-fw fa-deviantart',
            'class' => 'btn btn-xs btn-success',
            'href' => url('analyse')
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $simulation_notify = '';
        $simulation_notify_add_show = 0;
        $paid_add = '';

        $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
        if ($mconfig) {
            // 模拟代付显示
            if ($mconfig['simulation_paid_notify'] == 1) {
                $simulation_notify = <<<EOF
<a title="模拟代付修改列表" style="margin-bottom:6px;" class="btn btn-xs btn-success" href="simulation_notify" >
<i class="fa fa-fw fa-bolt"></i>
模拟代付修改列表
</a> 
EOF;
                $simulation_notify_add_show = 1;
            }
            // 手动代付开启
            if ($mconfig['manual_paid'] == 1) {
                $paid_add = <<<EOF
<a title="支付宝手动代付" style="margin-bottom:6px;" class="btn btn-xs btn-primary" href="add" >
<i class="fa fa-plus-circle"></i>
支付宝手动代付
</a> 
EOF;
            }
        }

        // 模拟代付修改
        $simulation_notify_add = [
            'title' => '模拟代付修改',
            'class' => 'btn btn-xs btn-default',
            'href' => url('simulation_notify_add', ['id' => '__id__']),
            'icon' => 'fa fa-fw fa-pencil',
            'target' => '_blank',
            'data-title' => '真的要模拟代付修改吗？',
            'data-tips' => '危险操作，请明白其中产生的结果！'
        ];

        // 超时失败处理
        $refund = [
            'title' => '超时失败处理',
            'class' => 'btn btn-xs btn-default',
            'href' => url('refund', ['id' => '__id__']),
            'icon' => 'fa fa-fw fa-power-off',
            'data-title' => '真的要按超时失败处理吗？',
            'data-tips' => '危险操作，请明白其中产生的结果！'
        ];

        if ($this->no_auth) {
            $simulation_notify = '';
            $simulation_notify_add_show = 0;
            // $paid_add = '';
        }

        // 代付异常订单
        $tips = '';
        $error_count = AlipayPaidOrderModel::where(['other_order_id' => 102, 'status' => 1])->count();
        if ($error_count) {
            $tips = "当前异常订单有{$error_count}个！";
        }
        $wait_count = AlipayPaidOrderModel::where(['status' => 1])->count();
        if ($wait_count) {
            // $tips .= "<font size='3' color='#f0ad4e'>支付宝代付订单处理中有{$wait_count}个！</font>";
        }
        if ($this->no_auth) {
            $tips = '';
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setPageTitle('支付宝代付订单列表') // 设置页面标题
            ->setTableName('payment_order_paid') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->addColumns($items) // 批量添加列
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButton('verify', ['title' => '验证订单', 'class' => 'btn btn-xs btn-default ajax-get', 'icon' => 'fa fa-fw fa-leaf', 'href' => url('verify', ['id' => '__id__'])])
            ->addRightButton('refund', $refund)
            ->addRightButton('simulation_notify_add', $simulation_notify_add)
            ->addRightButton('notify', ['title' => '通知', 'class' => 'ajax-get confirm', 'data-title' => '真的要通知吗？', 'data-tips' => '商户系统要能够处理重复通知！', 'icon' => 'fa fa-fw fa-forumbee', 'href' => url('notify', ['id' => '__id__'])])
            ->setSearchArea($search) // 设置搜索区域
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->setExtraHtml($paid_add, 'toolbar_top')
            ->setExtraHtml($simulation_notify, 'toolbar_bottom')
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('analyse', $analyse) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            ->replaceRightButton(['status' => ['<>', 1]], '', 'refund') // 替换右侧按钮
            ->replaceRightButton(['status' => ['in', '1,4']], '', 'notify') // 替换右侧按钮
            ->replaceRightButton(['create_time' => ['<', time() - 86400 * 30]], '', 'notify') // 替换右侧按钮
            ->replaceRightButton(['status' => ['<>', $simulation_notify_add_show]], '', 'simulation_notify_add') // 替换右侧按钮       
            ->replaceRightButton(['company' => ['not in', ['yhk', 'zdy', 'shoudong']]], '', 'simulation_notify_add') // 替换右侧按钮       
            ->setPageTips($tips)
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        $mconfig = MconfigModel::where(['id' => $this->merchant_id, 'status' => 1])->find();
        if ($mconfig) {
            if ($mconfig['manual_paid'] != 1) {
                $this->error('权限不足！');
            }
        }
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if (!is_numeric($data['cash'])) {
                $this->error('代付金额,请输入数字！');
            }
            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }
            $paid_info = MconfigModel::where(['id' => $data['merchant_id']])->find();
            if (!$paid_info || $paid_info['manual_paid'] != 1 || false === strpos($paid_info['trade_type'], 'paid')) {
                $this->error('商户没有权限或者没有开通代付！');
            }
            $info = PaymentCashModel::where(['merchant_id' => $data['merchant_id']])->find();
            if (!$info || $info['status'] == 0) {
                $this->error('商户钱包不存在！');
            }
            if ($paid_info['paid_green_channel_status'] == 0) {
                if ($info['paid_cash'] < $data['cash'] * 100) {
                    $msg_cash = $info['paid_cash'] / 100;
                    $this->error("代付金额不足，您最高代付金额为｛{$msg_cash}｝元！");
                }
            }

            $verify_status = false;
            $verify = VerificationcodeModel::where(['verification_code' => $data['verification_code'], 'merchant_id' => $this->merchant_id, 'status' => 1])->find();
            if (!$verify || $verify['timeout'] + $verify['create_time'] < time()) {
                $verify_status = true;
                //$this->error("验证码不存在或验证码过期！");
            }
            if ($verify_status) {
                $code = $data['verification_code'];
                $GoogleVerification = new \GoogleAuthenticator\Verification();
                $secret = UserModel::where(['id' => session('user_auth.uid')])->value('google_secret');
                if ($GoogleVerification->checkCode($code, $secret)) {
                    $verify_status = false;
                } else {
                    $verify_status = true;
                }
            }
            if ($verify_status) {
                $this->error("验证码不存在或验证码过期！");
            }

            $arr['version'] = '1.0';                                           // 版本号
            $arr['merchant_id'] = $data['merchant_id'];                        // 商户号
            $arr['merchant_order_id'] = $data['merchant_order_id'];            // 商户订单号
            $arr['app_id'] = $data['app_id'];                                  // 应用id
            $arr['cash'] = $data['cash'];                                      // 金额（元） 
            $arr['trade_type'] = 'paid';                                       // 交易类型
            $arr['body'] = $data['body'];                                      // 付款说明
            $arr['account'] = $data['account'];                                // 支付宝帐号
            $arr['name'] = $data['name'];                                      // 收款方姓名
            $arr['id_card'] = $data['id_card'];                                // 身份证号
            $arr['mobile'] = $data['mobile'];                                  // 手机号
            $arr['notify_open'] = $data['notify_open'];                        // 通知开关
            $arr['notify_url'] = $data['notify_url'];                          // 通知地址
            $arr['ip'] = Request::ip();                                        // ip
            $arr['user_id'] = 0;                                               // 用户ID
            $arr['channel_id'] = 0;                                            // 渠道ID
            $arr['format'] = 'json';                                           // 返回格式
            $arr['sign_type'] = 'md5';                                         // 签名类型
            $arr['extra'] = $data['extra'];                                    // 商户自定义备注
            $arr['start_time'] = time();                                       // 创建时间（时间戳）
            $arr['random_string'] = date('YmdHis') . rand(100000, 999999);     // 随机字符串

            $key = $paid_info['paid_key'];
            $arr['sign'] = md5('merchant_id=' . $arr['merchant_id'] . '&merchant_order_id=' . $arr['merchant_order_id'] . '&cash=' . $arr['cash'] . '&account=' . $arr['account'] . '&start_time=' . $arr['start_time'] . '&random_string=' . $arr['random_string'] . '&key=' . $key);

            $request_url = Request::domain() . '/api.php/order/alipayPaid';    // 请求地址
            $resdata = go_curl($request_url, $arr, 'post', 20);
            $resarray = json_decode($resdata, true);
            $msg = isset($resarray['msg']) ? $resarray['msg'] : '手动（未知错误）';

            if (isset($resarray['status']) && $resarray['status'] == 1) {
                AlipayPaidOrderModel::where(['merchant_order_id' => $arr['merchant_order_id'], 'merchant_id' => $arr['merchant_id']])->update(['mode' => 1, 'remark' => $this->merchant_id, 'update_time' => time()]);
                $arr['operation_id'] = $this->merchant_id;
                action_log('payment_order_paid_add', 'payment_order_paid', $arr['merchant_id'], UID, json_encode($arr));

                $this->success('操作成功', url('index'));
            } else {
                $this->error("失败说明：{$msg}");
            }
        }

        $merchants = MconfigModel::where([
            ['trade_type', 'like', '%' . 'paid' . '%'],
            ['manual_paid', '=', 1],
        ])->column('id');

        $users = UserModel::column('nickname', 'merchant_id');

        $all_merchant = getOneTwoArray($merchants, $users);

        $items = [
            ['select', 'merchant_id', '商户号', '', $all_merchant],
            ['text', 'cash', '代付金额', '请输入数字'],
            ['text', 'account', '支付宝帐号', '比如：邮箱或手机号'],
            ['text', 'name', '姓名', '收款姓名'],
            ['text', 'id_card', '身份证号', '不清楚填0', '0'],
            ['text', 'mobile', '手机号', '不清楚填0', '0'],
            ['text', 'app_id', '应用ID', '默认0', '0'],
            ['text', 'body', '付款说明', '默认：转账', '转账'],
            ['text', 'merchant_order_id', '商户订单号', '商户订单号', date('YmdHis') . rand(100000, 999999)],
            ['text', 'notify_url', '通知接收地址', '通知地址', Request::domain() . '/success.html'],
            ['radio', 'notify_open', '通知接收开关', '是否选择接收', ['关闭', '开启'], 0],
            ['text', 'extra', '商户自定义备注', '商户自定义备注'],
            ['text', 'verification_code', '验证码'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        if ($this->role > $this->have_auth) {
            unset($items[0]);
        }
        $hour_paid_send_max_count = pay_config('hour_paid_send_max_count');
        $tips = "默认验证码有效期是1个小时，发送验证码，点击一次即可，系统设置1个小时最多发送｛{$hour_paid_send_max_count}｝次验证码！"
            . "<br/>邮箱为空请联系客服绑定！您的绑定邮箱是:｛{$mconfig['email']}｝"
            . "<br/>手机号为空请联系客服绑定！您的绑定手机号是:｛{$mconfig['mobile']}｝</a>"
            . "<br/>支持谷歌验证码！</a>"
            . "<br/><br/><a title='点击发送验证码' class='btn btn-primary' href='sendVerify'> 点击发送验证码！</a>";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('支付宝手动代付') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->fetch();
    }

    /**
     * 发送验证码
     * @return mixed
     */
    public function sendVerify()
    {
        $mconfig = MconfigModel::where(['id' => $this->merchant_id, 'status' => 1])->find();
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            $email_mobile = $data['type'] ? $mconfig['mobile'] : $mconfig['email'];
            $msg_title = $data['type'] ? '手机号' : '邮箱';

            if ($email_mobile) {

                $temp_map[] = ['email_mobile', '=', $email_mobile];
                $temp_map[] = ['merchant_id', '=', $this->merchant_id];
                $temp_map[] = ['create_time', ['>=', time() - 3600], ['<', time()]];

                $count = VerificationcodeModel::where($temp_map)->count();
                $hour_paid_send_max_count = pay_config('hour_paid_send_max_count');
                if ($count >= $hour_paid_send_max_count) {
                    $this->error("一个小时内最多只能发送{$hour_paid_send_max_count}次！");
                }

                $data['id'] = date('YmdHis');
                $data['merchant_id'] = $this->merchant_id;
                $data['email_mobile'] = $email_mobile;
                $data['verification_code'] = rand(100000, 999999);
                $data['type'] = $data['type'];
                $data['timeout'] = 3600;
                $data['remark'] = "支付宝代付{$msg_title}验证码";
                $data['status'] = 1;

                $info = VerificationcodeModel::where(['id' => $data['id']])->find();
                if ($info) {
                    $this->error("请刷新，数据已经存在！");
                }

                $ins = VerificationcodeModel::create($data);
                if ($ins) {
                    $body = "您的商户号是｛{$data['merchant_id']}｝，验证码是｛{$data['verification_code']}｝";
                    // 邮箱
                    if ($data['type'] == 0) {
                        $res = send_mail($mconfig['email'], $data['merchant_id'], '验证码', $body);
                        if ($res === true) {
                            $this->success('发送成功！', url('add'));
                        }
                        payment_error_log(800000, $data, $res);
                        $this->error("发送失败！", url('index'));
                    }
                    // 手机号
                    if ($data['type'] == 1) {
                        $res = send_mobile($mconfig['mobile'], $data['verification_code']);
                        if ($res === true) {
                            $this->success('发送成功！', url('add'));
                        }
                        payment_error_log(800001, $data, $res);
                        $this->error("发送失败！", url('index'));
                    }
                }
                $this->error('发送失败！', url('index'));
            }
            $this->error("发送失败,{$msg_title}没有绑定！", url('index'));
        }

        $items = [
            ['radio', 'type', '类型', '', ['邮箱', '手机号'], 0],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        $hour_paid_send_max_count = pay_config('hour_paid_send_max_count');
        $tips = "默认验证码有效期是1个小时，发送验证码，点击一次即可，系统设置1个小时最多发送｛{$hour_paid_send_max_count}｝次验证码！"
            . "<br/>邮箱为空请联系客服绑定！您的绑定邮箱是:｛{$mconfig['email']}｝"
            . "<br/>手机号为空请联系客服绑定！您的绑定手机号是:｛{$mconfig['mobile']}｝";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('接收验证码') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->fetch();
    }

    /**
     * 分析
     * @return mixed
     */
    public function analyse()
    {
        $data = $this->request->get();
        // 保存数据
        if ($data) {

            $count = $data['count'] ? $data['count'] : 0;
            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }

            if ($data['merchant_id']) {
                $temp_map[] = ['merchant_id', '=', $data['merchant_id']];
            }
            if ($data['user_id']) {
                $temp_map[] = ['user_id', '=', $data['user_id']];
            }
            if ($data['account']) {
                $temp_map[] = ['account', '=', $data['account']];
            }
            if ($data['app_id']) {
                $temp_map[] = ['app_id', '=', $data['app_id']];
            }
            if ($data['create_param']) {
                $temp_map[] = ['create_param', 'like', '%' . $data['create_param'] . '%'];
            }
            if ($data['status']) {
                $temp_map[] = ['status', '=', $data['status']];
            }
            if (isset($data['child_company']) && $data['child_company']) {
                $temp_map[] = ['child_company', '=', $data['child_company']];
            }

            $temp_map[] = ['create_time', ['>=', strtotime($data['start_time'])], ['<', strtotime($data['end_time'])]];

            $list_rows = input('list_rows', 10);
            // 数据列表
            $data_list = Db::name('payment_order_alipay_paid')
                ->where($temp_map)
                ->field('merchant_id,user_id,account,name,app_id,count(account) as counts,sum(cash) as cashs')
                ->group('account')
                ->having("count(account)>={$count}")
                ->paginate($list_rows);

            // 分页数据
            $page = $data_list->render();

            $items = [
                ['__INDEX__', '#'],
                ['merchant_id', '商户', 'callback', function ($value) {
                    return $value . '<br/>' . get_user_nickname($value);
                }, '', 'text-center'],
                ['user_id', '用户ID'],
                ['account_name', '帐号和姓名', 'callback', function ($value) {
                    return $value['account'] . '<br/>' . $value['name'];
                }, '__data__', 'text-center'],
                ['app_id', '应用名称', 'callback', function ($value) {
                    return $value ? $value . '<br/>' . AlipayPaidOrderModel::appName($value) : '';
                }, '', 'text-center'],
                ['cashs', '总金额（元）', 'callback', function ($value) {
                    return $value / 100;
                }],
                ['counts', '次数'],
            ];

            // 使用ZBuilder快速创建数据表格
            return ZBuilder::make('table')
                ->hideCheckbox()
                ->setPageTitle('分析数据') // 设置页面标题
                ->addColumns($items) // 批量添加列
                ->setRowList($data_list) // 设置表格数据
                ->setPages($page) // 设置分页数据
                ->fetch(); // 渲染页面
        }

        // 所有的订单状态
        $all_order_status = [1 => '处理中', 2 => '成功', 3 => '失败', 4 => '异常'];

        // 代付公司    
        $paid_company = PaymentPaidCompanyModel::where(['paid_class' => [1, 2], 'status' => 1])->order('sort asc,name asc')->column('title', 'name');

        $start_time = date("Y-m-d");
        $end_time = date("Y-m-d") . ' 23:59:59';

        $items = [
            ['text', 'merchant_id', '商户号', ''],
            ['text', 'user_id', '用户ID', ''],
            ['text', 'account', '支付宝帐号', ''],
            ['text', 'app_id', '应用ID', ''],
            ['text', 'create_param', '其它参数', ''],
            ['text', 'count', '大于等于次数', '', 1],
            ['radio', 'status', '状态', '', $all_order_status, 2],
            ['select', 'child_company', '支付子公司', '', $paid_company],
            ['datetime', 'start_time', '开始日期', '', $start_time],
            ['datetime', 'end_time', '结束日期', '', $end_time],
        ];
        if ($this->no_auth) {
            unset($items[0]);
            unset($items[7]);
        }

        $tips = '分析支付宝代付数据！';

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('分析数据') // 设置页面标题
            ->setPageTips($tips)
            ->addFormItems($items)
            ->method('get')
            ->isAjax(false)
            ->fetch();
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        // 所有的订单状态
        $all_order_status = [1 => '处理中', 2 => '成功', 3 => '失败', 4 => '异常'];

        // 代付公司
        $all_config_group = pay_config('paid_company');
        // 代付公司子商户号
        $all_child_company = PaymentPaidCompanyModel::where(['paid_class' => [1, 2]])->order('sort asc,name asc')->column('title', 'name');

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $count = AlipayPaidOrderModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }
        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "支付宝代付订单导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败");
        }

        $field = [
            'order_id',
            'merchant_id',
            'merchant_order_id',
            'app_id',
            'cash',
            'deduct_cash',
            'balance',
            'paid_start_price',
            'paid_rate',
            'body',
            'name',
            'account',
            'mode',
            'status',
            'create_time',
            'update_time',
            'company',
            'child_company',
            'other_order_id',
        ];
        if ($this->no_auth) {
            unset($field[16]);
            unset($field[17]);
            unset($field[18]);
        }

        $cellName = [
            '平台订单号',
            '商户号',
            '商户订单号',
            '应用ID',
            '代付金额',
            '扣除金额',
            '代付余额',
            '每次代付开始扣除金额',
            '代付费率',
            '付款说明',
            '姓名',
            '支付宝帐号',
            '代付方法',
            '订单状态',
            '创建时间',
            '更新时间',
            '代付公司',
            '代付公司子商户号',
            '第三方订单号',
        ];
        if ($this->no_auth) {
            unset($cellName[16]);
            unset($cellName[17]);
            unset($cellName[18]);
        }
        $hide_info = 0;
        if ($this->no_auth) {
            $hide_info = 1;
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_order_alipay_paid')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_order_status, $all_config_group, $all_child_company, $hide_info) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;
                    $single['deduct_cash'] /= 100;
                    $single['balance'] /= 100;
                    $single['paid_start_price'] /= 100;
                    $single['status'] = $all_order_status[$single['status']];
                    $single['mode'] = $single['status'] == 1 ? '手动' : '自动';
                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;

                    if (isset($single['company'])) {
                        $single['company'] = isset($all_config_group[$single['company']]) ? $all_config_group[$single['company']] : $single['company'];
                    }
                    if (isset($single['child_company'])) {
                        $single['child_company'] = isset($all_child_company[$single['child_company']]) ? $all_child_company[$single['child_company']] : $single['child_company'];
                    }

                    if ($hide_info) {
                        $single['account'] = '****' . substr($single['account'], 4);
                    }

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['merchant_id', 'cash', 'deduct_cash', 'balance', 'paid_start_price'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 手动通知商户，订单完成
     * @param null $id 平台订单号
     * @return mixed
     */
    public function notify($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }
        // 获取数据
        $info = AlipayPaidOrderModel::where('order_id', $id)->field(true)->find();
        if (!$info || !in_array($info['status'], ['2', '3'])) {
            $this->error('参数有误！');
        }
        if (time() > $info['create_time'] + 86400 * 30) {
            $this->error('订单时间已经超过30天时间！');
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if (in_array($info['merchant_id'], $sub_merchant)) {
                $see_auth = true;
            }
        }

        if ($this->no_auth) {
            if (!isset($see_auth) && $this->merchant_id != $info['merchant_id']) {
                $this->error('通知有误！');
            }
        }

        // 把支付成功信息通知给商户
        $merchant_create_param = json_decode($info['create_param'], true);
        $notify_url = $merchant_create_param['notify_url'];
        $notify_data['code'] = 10000;                                         // 成功状态码
        $notify_data['merchant_id'] = $info['merchant_id'];                   // 商户号
        $notify_data['merchant_order_id'] = $info['merchant_order_id'];       // 商户订单号
        $notify_data['order_id'] = $info['order_id'];                         // 平台订单号
        $notify_data['app_id'] = $merchant_create_param['app_id'];            // 应用id
        $notify_data['cash'] = $info['cash'] ? $info['cash'] / 100 : 0;       // 代付现金    
        $notify_data['deduct_cash'] = $info['deduct_cash'] ? $info['deduct_cash'] / 100 : 0;  // 扣除金额    
        $notify_data['mode'] = $info['mode'];                                 // 代付方法：0自动，1手动
        $notify_data['trade_type'] = $merchant_create_param['trade_type'];    // 交易类型：比如充值、代付
        $notify_data['body'] = $merchant_create_param['body'];                // 代付说明
        $notify_data['time'] = time();                                        // 更新时间
        $notify_data['extra'] = $merchant_create_param['extra'];              // 商户自定义备注
        // 订单状态：1:处理中 2:成功 3:失败 4:异常
        $notify_data['status'] = $info['status'];
        $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&status=' . $notify_data['status'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);
        $resdata = go_curl($notify_url, $notify_data, 'get', 8);

        if (stripos($resdata, 'success') !== false) {
            // 通知成功     
            $this->error('通知成功');
        }

        $this->error("通知失败,返回内容是：{$resdata}");
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 所有的订单状态
        $all_order_status = [1 => '处理中', 2 => '成功', 3 => '失败', 4 => '异常'];
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 代付公司
        $all_config_group = pay_config('paid_company');
        // 代付公司子商户号
        $all_child_company = PaymentPaidCompanyModel::where(['paid_class' => [1, 2]])->order('sort asc,name asc')->column('title', 'name');

        // 获取数据
        $info = AlipayPaidOrderModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if (in_array($info['merchant_id'], $sub_merchant)) {
                $see_auth = true;
            }
        }

        if ($this->no_auth) {
            if (!isset($see_auth) && $this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        if (!$this->key_see_safe) {
            $create_param = json_decode($info['create_param'], true);
            if (isset($create_param['key'])) {
                unset($create_param['key']);
            }
            $info['create_param'] = json_encode($create_param);
            $info['verify_param'] = '';
        }

        $info['trade_type'] = $all_trade_type[$info['trade_type']];
        $info['cash'] /= 100;
        $info['deduct_cash'] = $info['deduct_cash'] ? $info['deduct_cash'] / 100 : 0;
        $info['paid_start_price'] = $info['paid_start_price'] ? $info['paid_start_price'] / 100 : 0;
        $info['balance'] = $info['balance'] ? $info['balance'] / 100 : 0;
        $info['mode'] = $info['mode'] == 1 ? '手动' : '自动';
        $info['status'] = $all_order_status[$info['status']];
        $info['company'] = isset($all_config_group[$info['company']]) ? $all_config_group[$info['company']] : '';
        $info['child_company'] = isset($all_child_company[$info['child_company']]) ? $all_child_company[$info['child_company']] : '';
        $info['create_param'] = format_nice($info['create_param']);
        $info['return_param'] = format_nice($info['return_param']);
        $info['notify_param'] = format_nice($info['notify_param']);

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id']), '', '', ''],
            ['static', 'app_id', '应用id', '', '', '', ''],
            ['static', 'cash', '代付现金（元）', ''],
            ['static', 'deduct_cash', '扣除金额（元）', ''],
            ['static', 'balance', '代付钱包余额（元）', ''],
            ['static', 'paid_start_price', '每次代付开始扣除金额', ''],
            ['static', 'paid_rate', '代付费率', ''],
            ['static', 'body', '付款说明'],
            ['static', 'account', '支付宝帐号', '', '', '', ''],
            ['static', 'name', '收款人姓名', '', '', '', ''],
            ['static', 'mode', '代付方式', '', '', '', ''],
            ['static', 'status', '订单状态', '', '', '', ''],
            ['static', 'trade_type', '交易类型', ''],
            ['datetime', 'create_time', '订单创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '订单更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['static', 'order_id', '平台订单号'],
            ['static', 'merchant_order_id', '商户订单号', '', '', '', ''],
            ['textarea', 'create_param', '创建数据[:无]', '', '', '', ''],
            ['textarea', 'return_param', '返回数据[:无]', '', '', '', ''],
            ['textarea', 'notify_param', '通知数据[:无]', '', '', '', ''],
            ['static', 'other_order_id', '第三方订单号', '', '', '', ''],
            ['static', 'company', '代付公司', '', '', '', ''],
            ['static', 'child_company', '代付公司子商户号'],
            ['static', 'remark', '备注'],
            ['radio', 'paid_green_channel_status', '商户代付绿色通道是否开启', '', ['禁用', '开启'], '', '', 'disabled'],
        ];
        if ($this->no_auth) {
            unset($items[18]);
            unset($items[19]);
            unset($items[20]);
            unset($items[21]);
            unset($items[22]);
            unset($items[23]);
            unset($items[24]);
        }
        if ($this->role > $this->have_auth) {
            unset($items[17]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 验证
     * @param  null      $id    平台订单号
     * @param  boolean   $rule  返回类型
     * @return mixed
     */
    public function verify($id = null, $rule = false)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        $info = AlipayPaidOrderModel::where(['order_id' => $id])->find();
        if (!$info) {
            $this->error('平台订单号不存在！');
        }

        $child_config = PaymentPaidCompanyModel::where(['name' => $info['child_company']])->column('*', 'name');
        $company_merge_values = $child_config[$info['child_company']];

        $send_order_id = $info['order_id'];
        $company_parent_name = $info['company'];
        if (in_array($company_parent_name, ['abcdefg'])) {
            $send_order_id = $info['other_order_id'] ?: $info['order_id'];
        }

        $companys = $company_parent_name . 'PaidQuery';
        // 实例化第三方订单模型
        $other_order_obj = new PaymentOrderAlipayPaidModel();
        // 发送给第三方公司    
        $resdata = $other_order_obj->$companys($send_order_id, $company_merge_values, $info->toArray(), false, false);
        $return_param = format_nice($resdata['return_param']);
        $resarray = json_decode($resdata['return_param'], true);
        $msg = '未知错误';
        $find = 0;

        if ($company_parent_name == 'shoudong') {
            $find = 1;
            switch ('1') {
                case '2':
                    $msg = '成功';
                    break;
                case '3':
                    $msg = '失败';
                    break;
                case '1':
                    $msg = '处理中';
                    break;
            }
        }

        if (isset($resarray['alipay_fund_trans_common_query_response']['status']) && $company_parent_name == 'zfb') {
            $find = 1;
            switch ($resarray['alipay_fund_trans_common_query_response']['status']) {
                case 'SUCCESS':
                    $msg = '成功';
                    break;
                case 'FAIL':
                    $msg = '失败';
                    break;
                case '1':
                    $msg = '处理中';
                    break;
            }
        }

        if (isset($resarray['alipay_fund_trans_order_query_response']['status']) && $company_parent_name == 'zfb') {
            $find = 1;
            switch ($resarray['alipay_fund_trans_order_query_response']['status']) {
                case 'SUCCESS':
                    $msg = '成功';
                    break;
                case 'FAIL':
                    $msg = '失败';
                    break;
                case '3':
                    $msg = '处理中';
                    break;
            }
        }

        if (isset($resarray['state']) && $company_parent_name == 'youyifu') {
            $find = 1;
            switch ($resarray['state']) {
                case '1':
                    $msg = '成功';
                    break;
                case '2':
                    $msg = '失败';
                    break;
                case '3':
                    $msg = '处理中';
                    break;
            }
        }

        if ($company_parent_name == 'xhx') {
            if (isset($resarray['code']) && $resarray['code'] > 1000) {
                $msg = '订单不存在';
            }
            if (isset($resarray['queryItems'][0]['orderStatus'])) {
                $find = 1;
                switch ($resarray['queryItems'][0]['orderStatus']) {
                    case '1':
                        $msg = '未处理';
                        break;
                    case '2':
                        $msg = '成功';
                        break;
                    case '3':
                        $msg = '失败';
                        break;
                    case '4':
                        $msg = '处理中';
                        break;
                }
            }
        }

        if ($company_parent_name == 'lsy') {
            if (isset($resarray['data']['planDetail'][0]['payState'])) {
                $find = 1;
                switch ($resarray['data']['planDetail'][0]['payState']) {
                    case '3':
                        $msg = '成功';
                        break;
                    case '4':
                        $msg = '失败';
                        break;
                    case '1':
                        $msg = '处理中';
                        break;
                }
            }
        }

        if ($rule) {
            return $find;
        }


        $res = <<<EOF
<div class='col-xs-12'>
<textarea class='form-control' rows='20' style='margin: 0px; height: 500px; width: 1000px;'>
$return_param
</textarea>
</div>                    
EOF;

        $this->error("提示：{$msg}！第三方返回结果为：{$res}");
    }

    /**
     * 第三方代付失败处理
     * @return mixed
     */
    public function refund($id = null)
    {
        if ($this->no_auth) {
            $this->error('权限不足！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            $info = AlipayPaidOrderModel::where(['order_id' => $id])->find();
            if (!$info) {
                $this->error('平台订单号不存在！');
            }
            if ($info['status'] == 2 || $info['status'] == 3) {
                $this->error('代付订单号状态有误！');
            }
            if (time() > $info['create_time'] + 86400 * 7) {
                $this->error('订单时间已经超过7天时间！');
            }
            $time_reduce = $info['update_time'] - $info['create_time'];
            if ($time_reduce < 8) {
                $this->error('不是订单超时问题！');
            }

            $res = $this->verify($id, true);
            if ($res) {
                $this->error('操作有误，属于正常订单！');
            }

            $info['operation_id'] = $this->merchant_id;
            $info['remark'] = '超时';
            $info['status'] = 3;
            $info['update_time'] = time();

            $notify = AlipayPaidSimulationNotifyModel::insert($info->toArray());
            if (!$notify) {
                $this->error('记录日志失败');
            }

            $update_info = AlipayPaidOrderModel::where(['order_id' => $id])->update(['status' => $info['status'], 'remark' => $info['remark'], 'update_time' => time()]);
            if (!$update_info) {
                $this->error('操作失败');
            }

            // 失败处理
            if ($info['status'] == 3) {

                if ($info['paid_green_channel_status'] == 0) {
                    // 捕获异常,扣除商户代付余额(还原)
                    try {
                        PaymentCashModel::where(['merchant_id' => $info['merchant_id']])
                            ->inc('paid_cash', $info['deduct_cash'])
                            ->dec('paid_sum_cash', $info['deduct_cash'])
                            ->dec('paid_count', 1)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        payment_error_log(800002, $info, $e->getMessage());
                    }
                }
            }

            // 把代付信息通知给商户
            $merchant_create_param = json_decode($info['create_param'], true);
            if ($merchant_create_param['notify_open'] == 1) {
                $notify_url = $merchant_create_param['notify_url'];
                $notify_data['code'] = 10000;                                         // 成功状态码
                $notify_data['merchant_id'] = $info['merchant_id'];                   // 商户号
                $notify_data['merchant_order_id'] = $info['merchant_order_id'];       // 商户订单号
                $notify_data['order_id'] = $info['order_id'];                         // 平台订单号
                $notify_data['app_id'] = $merchant_create_param['app_id'];            // 应用id
                $notify_data['cash'] = $info['cash'] ? $info['cash'] / 100 : 0;       // 代付现金    
                $notify_data['deduct_cash'] = $info['deduct_cash'] ? $info['deduct_cash'] / 100 : 0;  // 扣除金额    
                $notify_data['mode'] = $info['mode'];                                 // 代付方法：0自动，1手动
                $notify_data['trade_type'] = $merchant_create_param['trade_type'];    // 交易类型：比如充值、代付
                $notify_data['body'] = $merchant_create_param['body'];                // 代付说明
                $notify_data['time'] = time();                                        // 更新时间
                $notify_data['extra'] = $merchant_create_param['extra'];              // 商户自定义备注
                // 订单状态：1:处理中 2:成功 3:失败 4:异常
                $notify_data['status'] = 3;
                $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&status=' . $notify_data['status'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);
                $resdata = go_curl($notify_url, $notify_data, 'get', 8);
                if (stripos($resdata, 'success') !== false) {
                    // 通知成功     
                    $this->error('通知成功', url('simulation_notify'));
                }
                // 通知失败,准备多次通知
                $url_param = http_build_query($notify_data);
                $url = strpos($notify_url, '?') !== false ? $notify_url . '&' . $url_param : $notify_url . '?' . $url_param;

                $notify_array = [
                    'merchant_id' => $info['merchant_id'],
                    'merchant_order_id' => $info['merchant_order_id'],
                    'order_id' => $info['order_id'],
                    'other_order_id' => $info['other_order_id'],
                    'app_id' => $info['app_id'],
                    'cash' => $info['cash'],
                    'type' => 0,
                    'trade_type' => $info['trade_type'],
                    'status' => 0,
                    'manual' => 0,
                    'count' => 0,
                    'create_time' => $info['create_time'],
                    'update_time' => time(),
                    'url' => $url,
                    'remark' => substr($resdata, 0, 60000),
                ];

                // 插入多次通知数据库
                try {
                    NotifyModel::create($notify_array);
                } catch (\Exception $e) {
                    payment_error_log(800003, $notify_array, $e->getMessage());
                }

                $this->error("发送成功,但是通知失败：{$resdata}", url('simulation_notify'));
            }

            $this->error("操作成功", url('simulation_notify'));
        }

        $items = [
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('超时失败处理') // 设置页面标题
            ->addFormItems($items)
            ->isAjax(false)
            ->fetch();
    }

    /**
     * 代付修改列表
     * @return mixed
     */
    public function simulation_notify()
    {
        if ($this->no_auth) {
            $this->error('权限不足！');
        }

        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $list_rows = input('list_rows', 10) >= 10 ? 10 : input('list_rows');
        // 数据列表
        $data_list = AlipayPaidSimulationNotifyModel::where($map)->order('create_time desc')->paginate($list_rows);

        $sum_count = AlipayPaidSimulationNotifyModel::where($map)->count();
        $sum_cash = AlipayPaidSimulationNotifyModel::where($map)->sum('cash');
        $sum_cash /= 100;

        $sum_deduct_cash = AlipayPaidSimulationNotifyModel::where($map)->sum('deduct_cash');
        $sum_deduct_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        // 所有的订单状态
        $all_order_status = [1 => '处理中', 2 => '成功', 3 => '失败', 4 => '异常'];

        // 代付公司
        $all_paid_company = pay_config('paid_company');
        // 代付公司子商户号
        $all_child_company = PaymentPaidCompanyModel::where(['paid_class' => [1, 2]])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        foreach ($all_child_company as $key => $value) {
            $all_config_group[strstr($key, 'Paid', true)] = $all_paid_company[strstr($key, 'Paid', true)];
        }

        $date = date('Y-m-d');
        $appidName = '';
        if ($this->no_auth) {
            $appidName = $this->merchant_id;
        }
        $all_appid = AlipayPaidSimulationNotifyModel::appidName($appidName);
        $search = [
            ['daterange:6', 'create_time', '发起时间', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '代付状态', '', '', $all_order_status],
            ['select:3', 'app_id', '所属应用', '', '', $all_appid],
            ['text:3', 'merchant_order_id', '商户订单号'],
            ['text:3', 'cash', '代付金额'],
            ['text:3', 'account', '支付宝帐号'],
            ['text:3', 'name', '姓名'],
            ['text:3', 'order_id', '平台订单号'],
            ['select:3', 'mode', '代付方式', '', '', ['0' => '自动', '1' => '手动']],
            ['select:3', 'company', '总代付公司', '', '', $all_config_group],
            ['select:3', 'child_company', '子公司名称', '', '', $all_child_company],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'merchant_id', '商户号'],
            ['text:3', 'operation_id', '操作号'],
        ];

        $items = [
            ['create_time', '发起时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['operation_id', '操作', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_order_id', '商户订单号'],
            ['order_id', '平台订单号'],
            ['other_order_id', '第三方订单号'],
            ['user_id', '用户ID'],
            ['account_name', '帐号和姓名', 'callback', function ($value) {
                return $value['account'] . '<br/>' . $value['name'];
            }, '__data__', 'text-center'],
            ['app_id', '应用名称', 'callback', function ($value) {
                return $value ? AlipayPaidOrderModel::appName($value) : '';
            }, '', 'text-center'],
            ['cashs', '代付和扣除', 'callback', function ($value) {
                return $value['cash'] / 100 . '<br/>' . $value['deduct_cash'] / 100;
            }, '__data__', 'text-center'],
            ['update_time', '完成时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status', '', $all_order_status],
            ['child_company', '子公司', 'callback', function ($child_company, $all_child_company) {
                return isset($all_child_company[$child_company]) ? $all_child_company[$child_company] : $child_company;
            }, $all_child_company],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[9]);
            unset($search[10]);
            unset($search[11]);
            unset($search[12]);
            unset($search[13]);
            // 去掉显示列
            unset($items[1]);
            unset($items[2]);
            unset($items[5]);
            unset($items[12]);
        }

        $describe = [
            'title' => "总笔数：{$sum_count} 笔    总金额：{$sum_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('simulation_notify_export', ['map' => urlencode(json_encode($map))]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $simulation_notify_add = '';

        $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
        if ($mconfig) {
            // 模拟代付
            if ($mconfig['simulation_paid_notify'] == 1) {
                $simulation_notify_add = <<<EOF
<a title="新增模拟代付" style="margin-bottom:6px;" class="btn btn-xs btn-danger" href="simulation_notify_add" >
<i class="fa fa-plus-circle"></i>
新增模拟代付
</a> 
EOF;
            }
        }
        if ($this->no_auth) {
            $simulation_notify_add = '';
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setPageTitle('支付宝代付修改列表') // 设置页面标题
            ->setTableName('payment_order_paid_simulation_notify') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->addColumns($items) // 批量添加列
            ->addRightButton('simulation_notify_see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('simulation_notify_see', ['id' => '__id__'])], true)
            ->addRightButton('verify', ['title' => '验证订单', 'class' => 'btn btn-xs btn-default ajax-get', 'icon' => 'fa fa-fw fa-leaf', 'href' => url('verify', ['id' => '__id__'])])
            ->setSearchArea($search) // 设置搜索区域
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->setExtraHtml($simulation_notify_add, 'toolbar_top')
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            ->fetch(); // 渲染页面
    }

    /**
     * 模拟第三方代付订单
     * @return mixed
     */
    public function simulation_notify_add($id = null)
    {
        if ($this->no_auth) {
            $this->error('权限不足！');
        }
        $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
        if ($mconfig) {
            if ($mconfig['simulation_paid_notify'] != 1) {
                $this->error('权限不足！');
            }
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if (empty($data['order_id'])) {
                $this->error('请输入平台订单号！');
            }
            $remark = !empty($data['manual_remark']) ? $data['manual_remark'] : $data['remark'];
            if (empty($remark)) {
                $this->error('请输入备注！');
            }
            $simulation_company = '';
            if (!empty($data['one'])) {
                $simulation_company = $data['one'];
            }
            if (!empty($data['two'])) {
                $simulation_company = $data['two'];
            }

            $info = AlipayPaidOrderModel::where(['order_id' => $data['order_id']])->find();
            if (!$info) {
                $this->error('平台订单号不存在，请重新输入！');
            }
            if ($info['status'] == 2 || $info['status'] == 3) {
                $this->error('代付订单号状态有误！');
            }
            if (time() > $info['create_time'] + 86400 * 30) {
                $this->error('订单时间已经超过30天时间！');
            }

            $info['operation_id'] = $this->merchant_id;
            $info['remark'] = $remark;
            $info['status'] = $data['status'];
            $info['update_time'] = time();

            $notify = AlipayPaidSimulationNotifyModel::insert($info->toArray());
            if (!$notify) {
                $this->error('记录日志失败！');
            }

            $update['status'] = $data['status'];
            $update['remark'] = $remark;
            $update['update_time'] = time();
            if ($simulation_company) {
                $update['company'] = strstr($simulation_company, 'Paid', true);
                $update['child_company'] = $simulation_company;
                $update['remark'] = $remark . '>' . $info['child_company'];
            }

            $update_info = AlipayPaidOrderModel::where(['order_id' => $data['order_id']])->update($update);
            if (!$update_info) {
                $this->error('操作失败！');
            }

            // 失败处理
            if ($data['status'] == 3) {

                if ($info['paid_green_channel_status'] == 0) {
                    // 捕获异常,扣除商户代付余额(还原)
                    try {
                        PaymentCashModel::where(['merchant_id' => $info['merchant_id']])
                            ->inc('paid_cash', $info['deduct_cash'])
                            ->dec('paid_sum_cash', $info['deduct_cash'])
                            ->dec('paid_count', 1)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        payment_error_log(800004, $info, $e->getMessage());
                    }
                }
            }

            // 把代付信息通知给商户
            $merchant_create_param = json_decode($info['create_param'], true);
            if ($merchant_create_param['notify_open'] == 1) {
                $notify_url = $merchant_create_param['notify_url'];
                $notify_data['code'] = 10000;                                         // 成功状态码
                $notify_data['merchant_id'] = $info['merchant_id'];                   // 商户号
                $notify_data['merchant_order_id'] = $info['merchant_order_id'];       // 商户订单号
                $notify_data['order_id'] = $info['order_id'];                         // 平台订单号
                $notify_data['app_id'] = $merchant_create_param['app_id'];            // 应用id
                $notify_data['cash'] = $info['cash'] ? $info['cash'] / 100 : 0;       // 代付现金    
                $notify_data['deduct_cash'] = $info['deduct_cash'] ? $info['deduct_cash'] / 100 : 0;  // 扣除金额    
                $notify_data['mode'] = $info['mode'];                                 // 代付方法：0自动，1手动
                $notify_data['trade_type'] = $merchant_create_param['trade_type'];    // 交易类型：比如充值、代付
                $notify_data['body'] = $merchant_create_param['body'];                // 代付说明
                $notify_data['time'] = time();                                        // 更新时间
                $notify_data['extra'] = $merchant_create_param['extra'];              // 商户自定义备注
                // 订单状态：1:处理中 2:成功 3:失败 4:关闭
                $notify_data['status'] = $data['status'];
                $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&status=' . $notify_data['status'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);
                $resdata = go_curl($notify_url, $notify_data, 'get', 8);
                if (stripos($resdata, 'success') !== false) {
                    // 通知成功     
                    $this->success('通知成功', url('simulation_notify'));
                }
                // 通知失败,准备多次通知
                $url_param = http_build_query($notify_data);
                $url = strpos($notify_url, '?') !== false ? $notify_url . '&' . $url_param : $notify_url . '?' . $url_param;

                $notify_array = [
                    'merchant_id' => $info['merchant_id'],
                    'merchant_order_id' => $info['merchant_order_id'],
                    'order_id' => $info['order_id'],
                    'other_order_id' => $info['other_order_id'],
                    'app_id' => $info['app_id'],
                    'cash' => $info['cash'],
                    'type' => 0,
                    'trade_type' => $info['trade_type'],
                    'status' => 0,
                    'manual' => 0,
                    'count' => 0,
                    'create_time' => $info['create_time'],
                    'update_time' => time(),
                    'url' => $url,
                    'remark' => substr($resdata, 0, 60000),
                ];

                // 插入多次通知数据库
                try {
                    NotifyModel::create($notify_array);
                } catch (\Exception $e) {
                    payment_error_log(800005, $notify_array, $e->getMessage());
                }

                $this->success("发送成功,但是通知失败：{$resdata}", url('simulation_notify'));
            }

            $this->success("操作成功", url('simulation_notify'));
        }

        // 代付公司    
        $map[] = ['simulation_company_status', '=', 1];
        $map[] = ['paid_class',  'in', [1, 2]];
        $map[] = ['status', '=', 1];
        $map[] = ['group', 'in', ['yhk', 'zdy', 'shoudong']];

        $paid_company = PaymentPaidCompanyModel::where($map)->order('sort asc,title desc,name asc')->column('title', 'name');

        $items = [
            ['text', 'order_id', '平台订单号', '输入平台订单号24位', $id],
            ['radio', 'status', '状态', '', ['2' => '成功', '3' => '失败'], 2],
            ['radio', 'remark', '备注', '选择备注', ['超时' => '超时', '502' => '502', '504' => '504', '成功' => '成功', '失败' => '失败', '无' => '无'], '无'],
            ['textarea', 'manual_remark', '手动填写备注', '填写：会覆盖单选备注'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
            ['radio', 'mode', '模式', '<code>点击开启手动填写参数</code>', ['one' => '模式一', 'two' => '模式二'], 'one'],
            ['radio', 'one', '模拟替换代付公司', '', $paid_company],
            ['select', 'two', '模拟替换代付公司', '', $paid_company],
        ];
        if (empty($paid_company)) {
            array_pop($items);
            array_pop($items);
            array_pop($items);
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('修改支付宝代付订单号状态') // 设置页面标题
            ->setPageTips("这是一个危险操作,请明白其中的风险！会记录日志。")
            ->addFormItems($items)
            ->setTrigger('mode', 'one', 'one')
            ->setTrigger('mode', 'two', 'two')
            ->fetch();
    }

    /**
     * 模拟订单查看
     * @param null $id 平台订单号
     * @return mixed
     */
    public function simulation_notify_see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 所有的订单状态
        $all_order_status = [1 => '处理中', 2 => '成功', 3 => '失败', 4 => '异常'];
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 代付公司
        $all_config_group = pay_config('paid_company');
        // 代付公司子商户号
        $all_child_company = PaymentPaidCompanyModel::where(['paid_class' => [1, 2]])->order('sort asc,name asc')->column('title', 'name');

        // 获取数据
        $info = AlipayPaidSimulationNotifyModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        if (!$this->key_see_safe) {
            $create_param = json_decode($info['create_param'], true);
            if (isset($create_param['key'])) {
                unset($create_param['key']);
            }
            $info['create_param'] = json_encode($create_param);
            $info['verify_param'] = '';
        }

        $info['trade_type'] = $all_trade_type[$info['trade_type']];
        $info['cash'] /= 100;
        $info['deduct_cash'] = $info['deduct_cash'] ? $info['deduct_cash'] / 100 : 0;
        $info['paid_start_price'] = $info['paid_start_price'] ? $info['paid_start_price'] / 100 : 0;
        $info['balance'] = $info['balance'] ? $info['balance'] / 100 : 0;
        $info['mode'] = $info['mode'] == 1 ? '手动' : '自动';
        $info['status'] = $all_order_status[$info['status']];
        $info['company'] = isset($all_config_group[$info['company']]) ? $all_config_group[$info['company']] : '';
        $info['child_company'] = isset($all_child_company[$info['child_company']]) ? $all_child_company[$info['child_company']] : '';
        $info['create_param'] = format_nice($info['create_param']);
        $info['return_param'] = format_nice($info['return_param']);
        $info['notify_param'] = format_nice($info['notify_param']);

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id']), '', '', ''],
            ['static', 'app_id', '应用id', '', '', '', ''],
            ['static', 'cash', '代付现金（元）', ''],
            ['static', 'deduct_cash', '扣除金额（元）', ''],
            ['static', 'balance', '代付钱包余额（元）', ''],
            ['static', 'paid_start_price', '每次代付开始扣除金额', ''],
            ['static', 'paid_rate', '代付费率', ''],
            ['static', 'body', '付款说明'],
            ['static', 'account', '支付宝帐号', '', '', '', ''],
            ['static', 'name', '收款人姓名', '', '', '', ''],
            ['static', 'mode', '代付方式', '', '', '', ''],
            ['static', 'status', '订单状态', '', '', '', ''],
            ['static', 'trade_type', '交易类型', ''],
            ['datetime', 'create_time', '订单创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '订单更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['static', 'order_id', '平台订单号'],
            ['static', 'merchant_order_id', '商户订单号', '', '', '', ''],
            ['textarea', 'create_param', '创建数据[:无]', '', '', '', ''],
            ['textarea', 'return_param', '返回数据[:无]', '', '', '', ''],
            ['textarea', 'notify_param', '通知数据[:无]', '', '', '', ''],
            ['static', 'other_order_id', '第三方订单号', '', '', '', ''],
            ['static', 'company', '代付公司', '', '', '', ''],
            ['static', 'child_company', '代付公司子商户号'],
            ['static', 'remark', '备注'],
            ['radio', 'paid_green_channel_status', '商户代付绿色通道是否开启', '', ['禁用', '开启'], '', '', 'disabled'],
            ['static', 'operation_id', '操作号', '商户名称：' . get_user_nickname($info['operation_id']), '', '', ''],
        ];
        if ($this->no_auth) {
            unset($items[18]);
            unset($items[19]);
            unset($items[20]);
            unset($items[21]);
            unset($items[22]);
            unset($items[23]);
            unset($items[24]);
            unset($items[25]);
        }
        if ($this->role > $this->have_auth) {
            unset($items[17]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 模拟导出数据
     * @return mixed
     */
    public function simulation_notify_export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        // 所有的订单状态
        $all_order_status = [1 => '处理中', 2 => '成功', 3 => '失败', 4 => '异常'];

        // 代付公司
        $all_config_group = pay_config('paid_company');
        // 代付公司子商户号
        $all_child_company = PaymentPaidCompanyModel::where(['paid_class' => [1, 2]])->order('sort asc,name asc')->column('title', 'name');

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $count = AlipayPaidSimulationNotifyModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }
        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "模拟支付宝代付订单导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败");
        }

        $field = [
            'order_id',
            'operation_id',
            'merchant_id',
            'app_id',
            'cash',
            'deduct_cash',
            'balance',
            'paid_start_price',
            'paid_rate',
            'body',
            'name',
            'account',
            'status',
            'mode',
            'create_time',
            'update_time',
            'merchant_order_id',
            'company',
            'child_company',
            'other_order_id',
        ];
        if ($this->no_auth) {
            unset($field[17]);
            unset($field[18]);
            unset($field[19]);
        }

        $cellName = [
            '平台订单号',
            '操作号',
            '商户号',
            '应用ID',
            '代付金额',
            '扣除金额',
            '代付余额',
            '每次代付开始扣除金额',
            '代付费率',
            '付款说明',
            '姓名',
            '支付宝帐号',
            '状态',
            '模式',
            '创建时间',
            '更新时间',
            '商户订单号',
            '代付公司',
            '代付公司子商户号',
            '第三方订单号',
        ];
        if ($this->no_auth) {
            unset($cellName[17]);
            unset($cellName[18]);
            unset($cellName[19]);
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_order_alipay_paid_simulation_notify')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_order_status, $all_config_group, $all_child_company) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;
                    $single['deduct_cash'] /= 100;
                    $single['balance'] /= 100;
                    $single['paid_start_price'] /= 100;
                    $single['status'] = $all_order_status[$single['status']];
                    $single['mode'] = $single['status'] == 1 ? '手动' : '自动';
                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;

                    if (isset($single['company'])) {
                        $single['company'] = isset($all_config_group[$single['company']]) ? $all_config_group[$single['company']] : $single['company'];
                    }
                    if (isset($single['child_company'])) {
                        $single['child_company'] = isset($all_child_company[$single['child_company']]) ? $all_child_company[$single['child_company']] : $single['child_company'];
                    }

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'deduct_cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }
}
